package com.js.common.core;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.js.common.constant.BotConst;
import com.js.domian.model.bot.ApiResult;
import com.js.domian.model.bot.GroupMessage;
import com.js.domian.model.bot.PrivateMessage;
import com.js.domian.model.bot.analysis.MessageChain;
import com.js.service.bot.core.BotGroupService;
import com.js.service.bot.core.BotPrivateService;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Slf4j
public class BotWebSocketClient extends WebSocketClient {

    private BotGroupService botGroupService;
    private BotPrivateService botPrivateService;

    public BotWebSocketClient(URI serverUri, Map<String, String> httpHeaders) {
        super(serverUri, httpHeaders);
        this.botGroupService = SpringUtil.getBean(BotGroupService.class);
        this.botPrivateService = SpringUtil.getBean(BotPrivateService.class);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        log.info("[websocket {}] 连接成功", this.uri.toString());
    }

    @Override
    public void onMessage(String message) {
        JSONObject jsonObject = JSONUtil.parseObj(message);
        try {
            if (jsonObject.containsKey("echo") && jsonObject.containsKey("status") && jsonObject.containsKey("retcode") && jsonObject.containsKey("data")) {
                log.info("[websocket {}] 收到回复：{}", this.uri.toString(), message);
                try {
                    ApiResult apiResult = JSONUtil.toBean(message, ApiResult.class);
                    CompletableFuture<ApiResult> completableFuture = BotConst.completableFutureMap.get(apiResult.getEcho());
                    if (completableFuture != null) {
                        completableFuture.complete(apiResult);
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
                return;
            }
            if(GroupMessage.isSupport(jsonObject)){
                log.info("[websocket {}] 收到消息: {}", this.uri.toString(), message);
                GroupMessage groupMessage = JSONUtil.toBean(jsonObject, GroupMessage.class);
                MessageChain messageChain = new MessageChain();
                for (int i = 0; i < groupMessage.getMessage().size(); i++) {
                    messageChain.add(MessageTypeHandle.getMessage(groupMessage.getMessage().getJSONObject(i)));
                }
                botGroupService.baseSend(this, groupMessage.getGroupId(), groupMessage.getUserId(), messageChain);
            }else if(PrivateMessage.isSupport(jsonObject)){
                log.info("[websocket {}] 收到消息: {}", this.uri.toString(), message);
                PrivateMessage privateMessage = JSONUtil.toBean(jsonObject, PrivateMessage.class);
                MessageChain messageChain = new MessageChain();
                for (int i = 0; i < privateMessage.getMessage().size(); i++) {
                    messageChain.add(MessageTypeHandle.getMessage(privateMessage.getMessage().getJSONObject(i)));
                }
                if(StrUtil.isNotBlank(messageChain.toString().trim())){
                    botPrivateService.baseSend(this, privateMessage.getUserId(), messageChain.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        log.info("[websocket {}] 退出连接, code={}, reason={}, remote={}", this.uri.toString(), i, s, b);
    }

    @Override
    public void onError(Exception e) {
        log.info("[websocket {}] 连接错误={}", this.uri.toString(), e.getMessage());
    }
}
